import {
	HTTP_BASE_URL,
	HTPP_HEADER_KEY,
	HEADER,
	TOKEN_NAME
} from "../config/index";
import {
	useUserStore
} from "../store/index";
import {
	checkLogin,
	toLogin
} from "../common/lib/login";

// 八大常用请求动作类型
export type RequestType = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'CONNECT' | 'HEAD' | 'OPTIONS' | 'TRACE';
export interface OtherSet {
	// 使用需要用户登录才能请求
	noAuth: boolean,
	// 是否需要过滤请求再返回数据
	noVerify: boolean
}

/**
 * 处理请求头的内容
 * @param {boolean} noAuth 
 * @param {string} url 
 * @return 
 */ 
function baseHeader(
	noAuth: boolean, // 不需要用户登录也能请求
	url: string // 所请求的url地址
) {
	const header = HEADER;
	const userStore = useUserStore();
	if(!noAuth) {
		if(!userStore.token && !checkLogin()) {
			console.log(`${HTTP_BASE_URL + url}跳入：未登录`);
			toLogin()
			return null;
		}
	}
	
	if(userStore.token) header[TOKEN_NAME] = userStore.token;
	
	return header;
}

/**
 * 发送请求
 */
function baseRequest<T = any, V = any>(
	url: string, 
	method: RequestType, 
	data: T, 
	{
		// 使用需要用户登录才能请求
		noAuth = false,
		// 是否需要过滤请求再返回数据
		noVerify = false
	}, 
	responseType = "text" // 定义返回数据的类型
) {
	
	let Url = HTTP_BASE_URL;
	let	header = baseHeader(noAuth, url);
	
	if(!header) return Promise.reject({
		message: "未登录！"
	});

	return new Promise((reslove, reject) => {
		uni.request({
			url: Url + url,
			method: method || 'GET',
			header: header,
			data: data || {},
			responseType: responseType,
			success: (res) => {
				// const result = successResponse(res, noVerify);
				// console.log(result.message)
				// const {message} = result;
				
				// if(!result.ok) reject({
				// 				 data: result.data? result.data : {},
				// 				 message: result.message? result.message : ''
				// 				});
				// else reslove(result.data? result.data : {});
			},
			fail: (msg) => {
				// reject(failResponse(msg, url));
			}
		})
	});
}

const request: {
	[index: string]: Function
} = {};

['options', 'get', 'post', 'put', 'head', 'delete', 'trace', 'connect'].forEach((method) => {
	request[method] = <T>(api: string, data: T, opt: OtherSet, responseType: string) => baseRequest(api, method as RequestType, data, opt || {}, responseType)
});

export default request;